#!/bin/bash

this_time=`date +"%F(%T)"`;
dist_path="/home/java-dist";
# 0) 读取参数，清理备份文件
for i in "$@";do
	case $i in
		--clear)
			echo "清理备份文件..."
			rm -rf ${r'${'}dist_path}/backup/*.jar
		;;
	esac
done

# 1) 上传新程序
if [ ! -d ${r'${'}dist_path}/update ];then
  mkdir ${r'${'}dist_path}/update
fi
cd ${r'${'}dist_path}/update
rm -rf ${r'${'}dist_path}/update/*.jar
echo "[42;97m升级文件上传中……[m"
rz
while true
do
	read -p "升级文件上传完毕，是否继续发布? [y/n]" input
	case $input in
		[yY]*)
			echo "[42;97m发布进行中...[m"
			echo -e "\n"
			break
			;;
		[nN]*)
			exit
			;;
		*)
			echo "输入有误，仅支持输入y或n。"
			;;
	esac
done

# 2) 停服务
appid=`jps -l|grep ${artifactId}|awk '{print $1}'`;
if [ -n "$appid" ];then
 echo "[42;97m${artifactId} pid is:"$appid"[m";
 kill -9 $appid;
 echo "[42;97mkilled pid "$appid"[m";
else
 echo "[42;97m未找到${artifactId}服务进程[m";
fi

# 3) 备份jar
echo -e "\n"
echo "[42;97m备份文件${r'${'}dist_path}/backup/${artifactId}-$this_time.jar[m"
if [ ! -d ${r'${'}dist_path}/backup ];then
  mkdir ${r'${'}dist_path}/backup
fi
if [ -f ${r'${'}dist_path}/update/${artifactId}-1.0.jar ];then
  mv ${r'${'}dist_path}/${artifactId}-1.0.jar ${r'${'}dist_path}/backup/${artifactId}-$this_time.jar
  mv ${r'${'}dist_path}/update/${artifactId}-1.0.jar ${r'${'}dist_path}/
fi


# 4) 启动程序
echo -e "\n"
echo "[42;97m程序文件部署完成，开始运行。[m"
if [ ! -f ${r'${'}dist_path}/${artifactId}-1.0.jar ];then
 echo "未找到jar文件，启动终止！";
 exit;
fi

jdk8gc="-XX:+UseG1GC -XX:+ParallelRefProcEnabled -XX:+TieredCompilation -XX:+ExplicitGCInvokesConcurrent"
nohup java -jar -server ${r'${'}jdk8gc}  -Dfile.encoding=utf-8 -Dspring.profiles.active=prod ${r'${'}dist_path}/${artifactId}-1.0.jar >> /var/log/webapps/${artifactId}/standard.out  &

# 5) 打印日志
echo "[42;97正在准备打印日志[m"
echo -e "\n"
sleep 3
tail -200f /var/log/webapps/${artifactId}/${artifactId}-all.logback